import { Injectable } from '@nestjs/common';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Artist } from '../entities';
import { Transaction, TransactionRepository, Repository } from 'typeorm';
import * as _ from 'lodash';
import { UsersService } from '@/modules/users';

@Injectable()
export class ArtistsService extends TypeOrmCrudService<Artist> {
  constructor(
    @InjectRepository(Artist) repo,
    private readonly userService: UsersService,
  ) {
    super(repo);
  }

  async checkFollow(artistId: number, userId: number) {
    const artist = await this.repo.findOneOrFail(artistId, {
      relations: ['followers'],
    });
    const index = artist.followers.findIndex(user => user.id === userId);
    return index !== -1;
  }

  @Transaction()
  async addFollower(
    artistId: number,
    userId: number,
    @TransactionRepository(Artist)
    artistTranRepo?: Repository<Artist>,
  ) {
    const artist = await artistTranRepo.findOneOrFail(artistId, {
      relations: ['followers'],
    });
    const favdByUser = artist.followers.findIndex(user => user.id === userId);

    const data = _.pick(artist, ['id', 'followers', 'followersCount']);

    if (favdByUser === -1) {
      const user = await this.userService.findOne(userId);
      data.followers.push(user);
      data.followersCount++;
      await artistTranRepo.save(data);
    }

    return _.pick(data, ['id', 'followersCount']);
  }

  @Transaction()
  async removeFollower(
    artistId: number,
    userId: number,
    @TransactionRepository(Artist)
    artistTranRepo?: Repository<Artist>,
  ) {
    const artist = await artistTranRepo.findOneOrFail(artistId, {
      relations: ['followers'],
    });
    const favdByUser = artist.followers.findIndex(user => user.id === userId);

    const data = _.pick(artist, ['id', 'followers', 'followersCount']);

    if (favdByUser !== -1) {
      data.followers.splice(favdByUser, 1);
      data.followersCount--;
      await artistTranRepo.save(data);
    }

    return _.pick(data, ['id', 'followersCount']);
  }
}
